package logic

import (
	"errors"
	"fmt"
	"sync"
)

// OnlineManager
/*
	连接管理模块
*/
type OnlineManager struct {
	RoleMap map[string]*Role //管理的连接信息
	// connections sync.Map 优化
	onlineLock sync.RWMutex //读写连接的读写锁
}

// NewOnlineManager
/*
	创建一个在线集合管理
*/
func NewOnlineManager() *OnlineManager {
	return &OnlineManager{
		RoleMap: make(map[string]*Role),
	}
}

// Add 添加在线
func (onlineMgr *OnlineManager) Add(r *Role) {

	onlineMgr.onlineLock.Lock()
	defer onlineMgr.onlineLock.Unlock()
	// TODO 这个地方关系到 断线重连 等
	//if _, ok := onlineMgr.RoleMap[r.Data.Name]; ok {
	//	fmt.Println("角色登录时已经在线，id=", rt)
	//	return false
	//}
	onlineMgr.RoleMap[r.Data.Name] = r
	fmt.Println("login success: ", r.Data.Name)
}

// Remove 去除在线
func (onlineMgr *OnlineManager) Remove(r *Role) {
	onlineMgr.onlineLock.Lock()
	defer onlineMgr.onlineLock.Unlock()

	delete(onlineMgr.RoleMap, r.Data.Name)
	fmt.Println("logout :", r.Data.Name)
}

func (onlineMgr *OnlineManager) Get(rId string) (*Role, error) {
	onlineMgr.onlineLock.RLock()
	defer onlineMgr.onlineLock.RUnlock()

	if r, ok := onlineMgr.RoleMap[rId]; ok {
		return r, nil
	} else {
		return nil, errors.New("role not found")
	}
}

func (onlineMgr *OnlineManager) Len() int {
	return len(onlineMgr.RoleMap)
}
